package com.lsq.tucao.user.handler;

import com.lsq.tucao.user.response.JsonResult;
import com.lsq.tucao.user.response.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {

    /**
     * 参数解析失败异常处理
     */
    //状态码
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    //表示让Spring捕获到所有抛出的SignException异常，并交由这个被注解的方法处理
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public JsonResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) {

        log.error(request.getRequestURI() + ":参数解析失败", e);
        return new JsonResult("请求的URI:" + request.getRequestURI(), HttpStatus.BAD_REQUEST.value(), "参数解析失败");
    }


    /**
     * 不支持当前请求方法异常处理
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public JsonResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {

        log.error(request.getRequestURI() + ":不支持当前请求方法", e);
        return new JsonResult("请求的URI:" + request.getRequestURI(), HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持当前请求方法");

    }

    /**
     * 项目运行异常处理
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e, HttpServletRequest request) {

        log.error(request.getRequestURI() + ":服务运行异常", e);
        return new JsonResult("请求的URI:" + request.getRequestURI(), HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务运行异常");

    }


    /**
     * 自定义异常处理
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public JsonResult handleException(MyException e, HttpServletRequest request) {
        log.error(request.getRequestURI() + ":自定义内部异常", e.getMsg());
        return new JsonResult("请求的URI:" + request.getRequestURI(), e.getCode(), e.getMsg());
    }

}

